package m3_publishsubscribe;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception{
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.126.129");
        f.setUsername("admin");
        f.setPassword("admin");

        Channel channel = f.newConnection().createChannel();
        //先做三步：1、定义交换机  2、定义随机队列    3、绑定到交换机
        channel.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);
//        String queue = UUID.randomUUID().toString();
//        channel.queueDeclare(queue,false,true,true,null);
        //让rabbitMQ服务器来随机命名，非持久，独占，自动删除
        String queue = channel.queueDeclare().getQueue();

        //第三个参数对fanout交换机无效
        channel.queueBind(queue,"logs","");

        //收到消息后用来处理消息的回调对象
        DeliverCallback deliverCallback = new DeliverCallback(){

            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());

                System.out.println("接收到的消息：" + msg);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };


        //正常消费数据
        channel.basicConsume(queue,true, deliverCallback, cancelCallback);
    }

}
